package com.lanhao.aot.carrierintegration.cj;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpRequest;

public class CJKoreaExpressUtil {
	private static final Logger LOG = LoggerFactory.getLogger(CJKoreaExpressUtil.class);
	public static final String BASE_URL = "http://boot.hkdexpress.net";
	public static final String AUTH_URL = "/hkd-boot/api/v1/auth";
	public static final String ORDER_URL = "/hkd-boot/api/v1/order";
	public static final String LABEL_URL = "/hkd-boot/api/v1/label";
	public static final String USERNAME = "CL0001";
	public static final String PASSWORD = "CL0001";
	public static final String ServiceId = "YST-KR-CJ-SEA-NI-B2C";
	public static final String Country_Code = "KR";
	public static final Double DEFAULT_WEIGHT = 0.25d;

	public static void main(String[] args) {
		Map<String, String> authHeader = getAuthHeader(null);
		if (authHeader != null) {
			createOrder(authHeader);
//			getLabel(authHeader, "HPNI2204270005");
		}
		
	}

	public static Map<String, String> getAuthHeader(String token) {
		if(StringUtils.isNotBlank(token)) {
			Map<String, String> header = new HashMap<>();
			header.put("X-Access-Token", token);
			return header;
		}
		String authUrl = BASE_URL + AUTH_URL;
		JSONObject request = new JSONObject();
		request.put("username", USERNAME);
		request.put("password", PASSWORD);
		LOG.info("开始调用鉴权接口URL={}", authUrl);
		String respBody = HttpRequest.post(authUrl).body(request.toString()).timeout(5000).execute().body();
		LOG.info("结束调用鉴权接口reponse={}", respBody);
		if (StringUtils.isNotBlank(respBody)) {
			JSONObject responseObject = JSON.parseObject(respBody);
			boolean success = responseObject.getBoolean("success");
			if (success) {
				JSONObject resultObject = responseObject.getJSONObject("result");
				String accessToken = resultObject.getString("token");
				// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTEwNTA4OTYsInVzZXJuYW1lIjoiQ0wwMDAxIn0.Pt6mLE5njuE5WZYc4Ep_P4otNTuN-8OG2HMvJ4DIiHY
				// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTEwNTE3MjksInVzZXJuYW1lIjoiQ0wwMDAxIn0.l-lczt6IDdNlwxY5CFPpITW79P2fnQsHvm_WtKGoI_Y
				Map<String, String> header = new HashMap<>();
				header.put("X-Access-Token", accessToken);
				return header;
			} else {
				String message = responseObject.getString("message");
				LOG.info("获取token信息失败，message={}", message);
			}
		}
		return null;
	}
	
	
	public static void createOrder(Map<String, String> authHeader) {
		String orderUrl = BASE_URL + ORDER_URL;
		JSONObject request = new JSONObject();
		request.put("currency", "USD");
		JSONArray erpConsigneeList = new JSONArray();
		JSONObject erpConsignee = new JSONObject();
		erpConsignee.put("address1", "강원도 춘천시 시청길10번길 4-2 명곡사");
		erpConsignee.put("address2", "");
		erpConsignee.put("city", "");
//		erpConsignee.put("company", "Amazon Fulfillment Center");
		erpConsignee.put("country", Country_Code);
//		erpConsignee.put("email", "");
		erpConsignee.put("name", "이건국r");
		erpConsignee.put("phone", "010-9243-9596");
		erpConsignee.put("taxNumber", "");
		erpConsignee.put("state", "");
		erpConsigneeList.add(erpConsignee);
		request.put("erpConsigneeList", erpConsigneeList);
		
		JSONArray erpShipmentParcelList = new JSONArray();
		JSONObject erpShipmentParce = new JSONObject();
		erpShipmentParce.put("bulky", 0.000);
		erpShipmentParce.put("height", 0);
		erpShipmentParce.put("length", 0);
		erpShipmentParce.put("weight", DEFAULT_WEIGHT);
		erpShipmentParce.put("width", 0);
		
		JSONArray erpShipmentProductList = new JSONArray();
		JSONObject erpShipmentProduct = new JSONObject();
		erpShipmentProduct.put("frBrand", "");
		erpShipmentProduct.put("frHscode", "");
		erpShipmentProduct.put("frMeterial", "");
		erpShipmentProduct.put("frModel", "");
		erpShipmentProduct.put("frName", "AnHeStuff");
		erpShipmentProduct.put("frUsage", "");
		erpShipmentProduct.put("lcBrand", "");
		erpShipmentProduct.put("lcHscode", "");
		erpShipmentProduct.put("lcMeterial", "");
		erpShipmentProduct.put("lcModel", "");
		erpShipmentProduct.put("lcName", "安和货物");
		erpShipmentProduct.put("lcUsage", "");
		erpShipmentProduct.put("photoUrl", "");
		erpShipmentProduct.put("quantity", 1);
		erpShipmentProduct.put("shopUrl", "");
		erpShipmentProduct.put("sku", "");
		erpShipmentProduct.put("unit", "PCS");
		erpShipmentProduct.put("unitPrice", 0.0d);
		erpShipmentProduct.put("unitWeight", DEFAULT_WEIGHT);
		erpShipmentProductList.add(erpShipmentProduct);
		
		erpShipmentParce.put("erpShipmentProductList", erpShipmentProductList);
		
		erpShipmentParcelList.add(erpShipmentParce);
		
		request.put("erpShipmentParcelList", erpShipmentParcelList);
		request.put("reference", UUID.fastUUID().toString(true));
		request.put("serviceId", ServiceId);
		request.put("shipmentPieces", "1");
		request.put("shipmentWeight", 0.25d);
		LOG.info("开始调用下单接口URL={}，requestBody={}", orderUrl, request.toString());
		String respBody = HttpRequest.post(orderUrl).addHeaders(authHeader).body(request.toString()).timeout(20000).execute().body();
		LOG.info("结束调用下单接口respBody={}", respBody);
		if (StringUtils.isNotBlank(respBody)) {
			JSONObject responseObject = JSON.parseObject(respBody);
			boolean success = responseObject.getBoolean("success");
			if (success) {
				JSONObject resultObject = responseObject.getJSONObject("result");
				String serialNumber = resultObject.getString("serialNumber");
				JSONArray parcelsArray = resultObject.getJSONArray("parcels");
				if(parcelsArray != null && parcelsArray.size() > 0) {
					JSONObject parcelObject = parcelsArray.getJSONObject(0);
					String parcelSerialNumber = parcelObject.getString("serialNumber");
					String trackNo = parcelObject.getString("trackNo");
					LOG.info("下单成功，parcelSerialNumber={}, trackNo={} ", parcelSerialNumber, trackNo);
				}
				getLabel(authHeader, serialNumber);
			} else {
				String message = responseObject.getString("message");
				LOG.info("下单失败，message={}", message);
			}
		}
	}
	
	public static void getLabel(Map<String, String> authHeader, String shipmentSerialNumber) {
		String labelUrl = BASE_URL + LABEL_URL;
		Map<String, Object> requestForm = new HashMap<>();
		requestForm.put("shipmentSerialNumber", shipmentSerialNumber);
		LOG.info("开始调用获取标签接口URL={}，requestForm={}", labelUrl, requestForm.toString());
		String respBody = HttpRequest.post(labelUrl).addHeaders(authHeader).form(requestForm).timeout(20000).execute().body();
		LOG.info("结束调用获取标签接口respBody={}", respBody);
		if (StringUtils.isNotBlank(respBody)) {
			JSONObject responseObject = JSON.parseObject(respBody);
			boolean success = responseObject.getBoolean("success");
			if (success) {
				JSONObject resultObject = responseObject.getJSONObject("result");
				String labelContent = resultObject.getString("labelContent");
				String fileName = "D:/" + UUID.fastUUID().toString(true) + ".pdf";
				Base64.decodeToFile(labelContent, new File(fileName));
				LOG.info("标签获取成功，已保存至路径path={}", fileName);
			} else {
				String message = responseObject.getString("message");
				LOG.info("获取标签失败，message={}", message);
			}
		}
	}
}
